﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ClickNET;
using ClickNET.Imaging;

public partial class image : System.Web.UI.Page
{
    private Gallery m_gallery;

    private static readonly string s_galleryDirectory = Config.DefaultInstance.GetConfigString("gallery", "imageDirectory");
    private static readonly string s_thumbsDirectory = Config.DefaultInstance.GetConfigString("gallery", "thumbsDirectory");
    private static readonly string s_thumbsFilePrefixFormat = Config.DefaultInstance.GetConfigString("gallery", "thumbsFilePrefixFormat");

    protected void Page_Load(object sender, EventArgs e)
    {
        string galleryName = Request["galleryName"];
        string fileName = Request["fileName"];
        int thumbSize = 0;
        int.TryParse(Request["thumbSize"], out thumbSize);

        if (!String.IsNullOrEmpty(galleryName) && !String.IsNullOrEmpty(fileName))
        {
            this.m_gallery = FileSystemGalleryManager.LoadGallery(galleryName);

            if (null != this.m_gallery)
            {
                Picture p = this.m_gallery.Pictures.Find(delegate(Picture pic) { return pic.FileName == fileName; });
                string filePath = string.Empty;

                if (null == p)
                    this.StreamImage(Server.MapPath("/") + "images/DoesNotExist_100.jpg");
                else
                {
                    string thumbPath = FileSystemGalleryManager.GetThumbnailFilesystemPath(p, thumbSize);
                    string fullSizePath = p.Path;
                    filePath = !File.Exists(thumbPath) ? p.Path : thumbPath;

                    this.StreamImage(filePath);
                }
            }
        }
    }

    private void StreamImage(string fullPath)
    {
        MemoryStream memStream = new MemoryStream();
        string mimetype = this.GetMimeType(fullPath);

        Response.ContentType = mimetype;

        // Buffer response so that page is sent
        // after processing is complete.
        Response.BufferOutput = true;

        System.Drawing.Image img = Bitmap.FromFile(fullPath);
        img.Save(memStream, img.RawFormat);
        memStream.WriteTo(Response.OutputStream);
    }

    private string GetMimeType(string Filename)
    {
        string mime = "application/octetstream";
        string ext = System.IO.Path.GetExtension(Filename).ToLower();
        Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
        if (rk != null && rk.GetValue("Content Type") != null)
            mime = rk.GetValue("Content Type").ToString();
        return mime;
    } 
}
